using System;
using System.Collections.Generic;
using System.Data;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Windows.Forms;
using Microsoft.Win32;
using MySql.Data.MySqlClient;
using ODT.Common.Core;
using ODT.Common.ExtensionMethods;
using ODT.Common.Services;
using ODT.Common.VisualStudio.Core;
using ODT.GlobalMessageProcessor;
using ODT.PMACGlobal;
using ODT.PPMACDatabase;

namespace IntellisenseControl
{
	public static class PPIntellisense
	{
		internal struct IPProperties
		{
			public string ipaddress;

			public string username;

			public string password;

			public IPProperties(string ip, string usr, string pw)
			{
				ipaddress = ip;
				username = usr;
				password = pw;
			}
		}

		public struct Lngspecific
		{
			public string name;

			public string comment;

			public Lngspecific(string nm, string tp)
			{
				name = nm;
				comment = tp;
			}
		}

		private static Dictionary<string, IPProperties> IPDict;

		private static Dictionary<string, List<string>> Level0Dictionary;

		private static Dictionary<string, List<string>> UserDictionary;

		private static object TableLock;

		private static readonly IOutputWindowService OutputWindowService;

		private static readonly IDatabaseService DatabaseService;

		static PPIntellisense()
		{
			IPDict = new Dictionary<string, IPProperties>();
			Level0Dictionary = new Dictionary<string, List<string>>();
			UserDictionary = new Dictionary<string, List<string>>();
			TableLock = new object();
			//OutputWindowService = ServiceManager.GetService<IOutputWindowService>();
			DatabaseService = ServiceManager.GetService<IDatabaseService>();
		}

		public static void SubscribeToEvents()
		{
			MessageReceiverClass messageReceiverClass = new MessageReceiverClass(MessageReceiverClass.SyncType.GlobalResetActive);
			MessageReceiverClass messageReceiverClass2 = new MessageReceiverClass(MessageReceiverClass.SyncType.GlobalConnect);
			MessageReceiverClass messageReceiverClass3 = new MessageReceiverClass(MessageReceiverClass.SyncType.GlobalDatabaseSync);
			MessageReceiverClass messageReceiverClass4 = new MessageReceiverClass(MessageReceiverClass.SyncType.GlobalResetComplete);
			MessageReceiverClass messageReceiverClass5 = new MessageReceiverClass(MessageReceiverClass.SyncType.GlobalRebootComplete);
			messageReceiverClass.PPMACGlobalResetActiveEvent += _ResetActive_PPMACGlobalResetActiveEvent;
			messageReceiverClass2.PPMACGlobalConnectEvent += _IPAdressChange_PPMACGlobalIPAddressChangeEvent;
			messageReceiverClass3.PPMACGlobalDatabaseSyncEvent += _DatabaseSync_PPMACGlobalDatabaseSyncEvent;
			messageReceiverClass4.PPMACGlobalResetCompleteEvent += _ResetComplete_PPMACGlobalResetCompleteEvent;
			messageReceiverClass5.PPMACGlobalRebootCompleteEvent += _RebootComplete_PPMACGlobalRebootCompleteEvent;
		}

		public static List<string> CreateLevel0LanguageList(string connectionString)
		{
			List<string> result = new List<string>();
			try
			{
				result = PopulateLevel0Tbl(connectionString);
			}
			catch
			{
			}
			return result;
		}

		public static List<string> CreateUserVariableSpecificList(string connectionString)
		{
			List<string> result = new List<string>();
			try
			{
				result = PopulateUserTbl(connectionString);
			}
			catch
			{
			}
			return result;
		}

		public static string GetHelpTextFromQuery(string[] queryText, string connectionString)
		{
			MySqlCommand mySqlCommand = new MySqlCommand();
			MySqlConnection mySqlConnection = new MySqlConnection();
			string text = string.Empty;
			try
			{
				if (!DatabaseService.IsDatabaseRunning())
				{
					return text;
				}
			}
			catch { }

			try
			{
				mySqlCommand.CommandType = CommandType.Text;
				for (int i = 0; i < queryText.Length; i++)
				{
					if (string.IsNullOrEmpty(queryText[i]))
					{
						continue;
					}
					mySqlCommand.CommandText = queryText[i];
					mySqlConnection.ConnectionString = connectionString;
					OpenMySQLConnection(mySqlConnection);
					mySqlCommand.Connection = mySqlConnection;
					MySqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();
					while (mySqlDataReader.Read())
					{
						text = mySqlDataReader.GetString(0).Trim();
					}
					mySqlConnection.Close();
					int num = -1;
					for (int j = 40; j < text.Length; j += 40)
					{
						num = text.IndexOf(' ', j);
						if (num > -1)
						{
							text = text.Insert(num + 1, "\r\n");
							j = num;
						}
					}
					if (!string.IsNullOrEmpty(text))
					{
						break;
					}
				}
				return text;
			}
			catch
			{
				return text;
			}
			finally
			{
				mySqlConnection.Close();
			}
		}

		public static string PopulateStringFromQuery(string text, string connectionString)
		{
			MySqlCommand mySqlCommand = new MySqlCommand();
			MySqlConnection mySqlConnection = new MySqlConnection();
			try
			{
				if (!DatabaseService.IsDatabaseRunning())
				{
					return string.Empty;
				}
			}
			catch { }

			string result = string.Empty;
			mySqlCommand.CommandType = CommandType.Text;
			mySqlCommand.CommandText = text;
			try
			{
				mySqlConnection.ConnectionString = connectionString;
				OpenMySQLConnection(mySqlConnection);
				mySqlCommand.Connection = mySqlConnection;
				MySqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();
				while (mySqlDataReader.Read())
				{
					result = mySqlDataReader.GetString(0).Trim();
				}
			}
			catch
			{
			}
			finally
			{
				mySqlConnection.Close();
			}
			return result;
		}

		public static List<string> GetAllOtherLevelList(ref string[] queryText, string connectionString)
		{
			MySqlCommand mySqlCommand = new MySqlCommand();
			MySqlConnection mySqlConnection = new MySqlConnection();
			List<string> list = new List<string>();
			try
			{
				if (!DatabaseService.IsDatabaseRunning())
				{
					return list;
				}
			}
			catch { }

			try
			{
				for (int i = 0; i < queryText.Length; i++)
				{
					mySqlCommand.CommandType = CommandType.Text;
					if (!string.IsNullOrEmpty(queryText[i]))
					{
						mySqlCommand.CommandText = queryText[i];
						mySqlConnection.ConnectionString = connectionString;
						OpenMySQLConnection(mySqlConnection);
						mySqlCommand.Connection = mySqlConnection;
						MySqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();
						while (mySqlDataReader.Read())
						{
							list.Add(mySqlDataReader.GetString(0).Trim());
						}
						mySqlConnection.Close();
					}
				}
			}
			catch
			{
			}
			finally
			{
				mySqlConnection.Close();
			}
			return list;
		}

		public static void RefreshTablesForReloading(string ip)
		{
			string key = DatabaseService.GetConnectionString("ppmac") + ip.Replace('.', '_');
			Level0Dictionary.Remove(key);
			UserDictionary.Remove(key);
		}

		private static List<string> PopulateLevel0Tbl(string connectionString)
		{
			lock (TableLock)
			{
				if (Level0Dictionary.ContainsKey(connectionString) && Level0Dictionary[connectionString].Count > 0)
				{
					return new List<string>(Level0Dictionary[connectionString]);
				}
				MySqlCommand mySqlCommand = new MySqlCommand();
				MySqlConnection mySqlConnection = new MySqlConnection();
				string[] array = new string[5];
				List<string> list = new List<string>();
				try
				{
					if (!DatabaseService.IsDatabaseRunning())
					{
						return list;
					}

					array[0] = "SELECT software_tbl0.Command FROM software_tbl0 where UserLevel < 4 order by Command";
					array[1] = "SELECT Name FROM userprog where Type like 'PROG' or Type like 'SUBPROG' or Type like 'PLC' order by Name";
					for (int i = 0; i <= 1; i++)
					{
						mySqlCommand.CommandType = CommandType.Text;
						mySqlCommand.CommandText = array[i];
						mySqlConnection.ConnectionString = connectionString;
						OpenMySQLConnection(mySqlConnection);
						mySqlCommand.Connection = mySqlConnection;
						MySqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();
						while (mySqlDataReader.Read())
						{
							list.Add(mySqlDataReader.GetString(0).Trim());
						}
						mySqlConnection.Close();
					}
				}
				catch
				{
				}
				finally
				{
					mySqlConnection.Close();
				}
				Level0Dictionary[connectionString] = list;
				return new List<string>(list);
			}
		}

		private static List<string> PopulateUserTbl(string connectionString)
		{
			lock (TableLock)
			{
				if (UserDictionary.ContainsKey(connectionString) && UserDictionary[connectionString].Count > 0)
				{
					return new List<string>(UserDictionary[connectionString]);
				}
				MySqlCommand mySqlCommand = new MySqlCommand();
				MySqlConnection mySqlConnection = new MySqlConnection();
				string[] array = new string[5];
				List<string> list = new List<string>();
				try
				{
					if (!DatabaseService.IsDatabaseRunning())
					{
						return list;
					}
					array[0] = "SELECT Name,Type FROM userglobal where Type like 'Ptr' or Type like 'Global' or Type like 'Csglobal' or Type like 'UserDefine'";
					for (int i = 0; i < 1; i++)
					{
						mySqlCommand.CommandType = CommandType.Text;
						mySqlCommand.CommandText = array[i];
						try
						{
							mySqlConnection.ConnectionString = connectionString;
							OpenMySQLConnection(mySqlConnection);
							mySqlCommand.Connection = mySqlConnection;
							MySqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();
							while (mySqlDataReader.Read())
							{
								list.Add(mySqlDataReader.GetString(0).Trim());
							}
						}
						catch
						{
						}
						finally
						{
							mySqlConnection.Close();
						}
					}
				}
				catch
				{
					mySqlConnection.Close();
				}
				mySqlConnection.Close();
				UserDictionary[connectionString] = list;
				return new List<string>(list);
			}
		}

		private static void OpenMySQLConnection(MySqlConnection connection)
		{
			try
			{
				int num = 0;
				while (connection.State != 0 && num < 100)
				{
					Thread.Sleep(10);
					num++;
				}
				if (connection.State != 0)
				{
					connection.Close();
				}
				connection.Open();
			}
			catch
			{
			}
		}

		private static void _IPAdressChange_PPMACGlobalIPAddressChangeEvent(object sender, MessageReceiverClass.IPChangeMessageReceiverEvnetArgs e)
		{
			if (e.handle.ToInt32() == IDEGlobals.VSHandle.ToInt32() && !e.ipAddress.IsNoDevice())
			{
				SynchronizeDataBase(e.ipAddress, e.username, e.pwd);
				RefreshTablesForReloading(e.ipAddress);
			}
		}

		private static void _ResetActive_PPMACGlobalResetActiveEvent(object sender, MessageReceiverClass.IPChangeMessageReceiverEvnetArgs e)
		{
			RefreshTablesForReloading(e.ipAddress);
		}

		private static void _DatabaseSync_PPMACGlobalDatabaseSyncEvent(object sender, MessageReceiverClass.DataSyncMessageReceiverEvnetArgs e)
		{
			GetIpAddressList();
			IPProperties value;
			if (!IPDict.TryGetValue(e.ipAddress, out value))
			{
				value.ipaddress = e.ipAddress;
				value.username = "root";
				value.password = "deltatau";
			}
			SynchronizeDataBase(e.ipAddress, value.username, value.password);
			RefreshTablesForReloading(e.ipAddress);
		}

		private static void _RebootComplete_PPMACGlobalRebootCompleteEvent(object sender, MessageReceiverClass.IPChangeMessageReceiverEvnetArgs e)
		{
			SynchronizeDataBase(e.ipAddress, e.username, e.pwd);
			RefreshTablesForReloading(e.ipAddress);
		}

		private static void _ResetComplete_PPMACGlobalResetCompleteEvent(object sender, MessageReceiverClass.IPChangeMessageReceiverEvnetArgs e)
		{
			SynchronizeDataBase(e.ipAddress, e.username, e.pwd);
			RefreshTablesForReloading(e.ipAddress);
		}

		private static void SynchronizeDataBase(string IPAddress, string username, string password)
		{
			PPDBUtilFunctions pPDBUtilFunctions = new PPDBUtilFunctions();
			pPDBUtilFunctions.DBUtilLogMessage += _database_DBUtilLogMessage;
			pPDBUtilFunctions.ResetDataSyncFlag(IPAddress);
			pPDBUtilFunctions.CheckDatabaseIntegrity(IPAddress, username, password);
			pPDBUtilFunctions.DBUtilLogMessage -= _database_DBUtilLogMessage;
		}

		private static void _database_DBUtilLogMessage(object sender, PPDBUtilFunctions.DbUtilLogArg e)
		{
			//OutputWindowService.Write(OutputWindowPane.DeltaTau, e.Message);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static void DummyDoNothing()
		{
		}

		internal static void GetIpAddressList()
		{
			IPDict = new Dictionary<string, IPProperties>();
			RegistryKey registryKey = Registry.CurrentUser;
			try
			{
				registryKey = Registry.CurrentUser.CreateSubKey("SOFTWARE\\Delta Tau Data Systems Inc\\4\\PowerPMAC IDE\\Devices");
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
			string[] subKeyNames = registryKey.GetSubKeyNames();
			foreach (string name in subKeyNames)
			{
				RegistryKey registryKey2 = registryKey.OpenSubKey(name);
				string text = (string)registryKey2.GetValue("IPAddress");
				if (!string.IsNullOrEmpty(text))
				{
					if (IPDict.ContainsKey(text))
					{
						IPDict[text] = new IPProperties(text, (string)registryKey2.GetValue("User"), (string)registryKey2.GetValue("Password"));
					}
					else
					{
						IPDict.Add(text, new IPProperties(text, (string)registryKey2.GetValue("User"), (string)registryKey2.GetValue("Password")));
					}
				}
			}
		}
	}
}
